Page({
  data: {
    newStudent: {
      studentName: '',
      studentNumber: ''
    },
    addedStudents: [],
    isEdit: false,
    courseId: '',
    weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    timeSlots: ['第一节', '第二节', '第三节', '第四节', '第五节', '第六节', '第七节', '第八节'],
    reminderTimes: ['不提醒', '提前5分钟', '提前10分钟', '提前15分钟', '提前30分钟'],
    formData: {
      startDate: '',
      totalWeeks: '',
      courseName: '',
      className: '',
      classroom: '',
      weekday: 0,
      timeSlot: 0,
      startTime: '00:00',
      endTime: '00:00',
      reminder: false,
      reminderTimeIndex: 0
    },
    showDatePicker: false,
    datePickerValue: [0, 0, 0], // 默认选中索引
    years: [],
    months: Array.from({length: 12}, (_, i) => i + 1),
    days: Array.from({length: 31}, (_, i) => i + 1)
  },

 // 处理新增学生输入
 handleNewStudentInput(e) {
  const { field } = e.currentTarget.dataset;
  this.setData({
    // 更新 newStudent 对象中的相应字段
    [`newStudent.${field}`]: e.detail.value
  });
},

// 添加新学生到列表
addNewStudent() {
  const { newStudent, addedStudents } = this.data;
  // 检查学生姓名和学号是否都已输入
  if (newStudent.studentName && newStudent.studentNumber) {
    const newAddedStudents = [...addedStudents, newStudent];
    this.setData({
      addedStudents: newAddedStudents,
      // 清空输入框
      newStudent: {
        studentName: '',
        studentNumber: ''
      }
    });
    console.log('add->',newAddedStudents)
  } else {
    wx.showToast({ title: '请输入完整的学生信息', icon: 'none' });
  }
},


// 删除已添加的学生
async deleteAddedStudent(e) {
  const { index } = e.currentTarget.dataset;
  const { addedStudents } = this.data;
  const studentToDelete = addedStudents[index];
  const studentId = studentToDelete._id;
  const courseId = this.data.courseId;

  try {
    if (studentId) {
      // 学生已存入数据库，进行数据库删除操作
      wx.showLoading({ title: '删除中...' });
      const db = wx.cloud.database();

      // 删除课程和学生的关联信息
      await db.collection('course_students').where({
        courseId,
        studentId
      }).remove();

      // 删除学生信息
      await db.collection('students').doc(studentId).remove();

      wx.hideLoading();
      wx.showToast({ title: '删除成功', icon: 'success' });
    } else {
      // 学生未存入数据库，仅从前端数组中移除
      wx.showToast({ title: '删除成功', icon: 'success' });
    }

    const newAddedStudents = addedStudents.filter((_, i) => i!== index);
    this.setData({
      addedStudents: newAddedStudents
    });

    console.log('delete->', newAddedStudents);
  } catch (err) {
    console.error('删除学生信息失败：', err);
    wx.hideLoading();
    wx.showToast({ title: '删除失败', icon: 'none' });
  }
},

  onLoad(options) {
    // 设置默认日期（当前日期）
    const defaultDate = this.formatDate(new Date())
    // 清空添加的数据 addedStudents 和 newStudent
    this.setData({
      formData:{
        ...this.data.formData,
        startDate: defaultDate,
      },
      addedStudents: [],
      newStudent: {
        studentName: '',
        studentNumber: ''
      }
    });

    // 同时加载数据并显示
    if (options.courseId) {
      this.setData({
        isEdit: true,
        courseId: options.courseId
      })
      this.fetchCourseDetail(options.courseId)
    } else if (options.weekday && options.timeSlot) {
      // 新增时预填时间段
      this.setData({
        'formData.weekday': parseInt(options.weekday) ,
        'formData.timeSlot': parseInt(options.timeSlot) 
      })
    }
  },

    // 处理提醒时间选择
    handleReminderTimeChange(e) {
      this.setData({
        'formData.reminderTimeIndex': parseInt(e.detail.value)
      })
    },
  
     // 请求订阅消息授权
requestSubscribeMessage() {
  console.info('[上课提醒] 开始请求订阅消息授权');
  // 从全局配置或缓存中获取模板ID
  const app = getApp();
  const templateId = app.globalData.subscribeTemplateId || 'FjvVLdPWxHONyFtFa5cqCknQX8Lex-R0cqVyGnSDHUY';
  console.info('[上课提醒] 使用的模板ID:', templateId);
  
  wx.requestSubscribeMessage({
    tmplIds: [templateId],
    success: (res) => {
      console.info('[上课提醒] 订阅请求结果:', JSON.stringify(res));
      if (res[templateId] === 'accept') {
        // 用户接受订阅
        console.info('[上课提醒] 用户接受订阅');
        this.saveSubscriptionStatus();
        wx.showToast({
          title: '订阅成功',
          icon: 'success'
        });
      } else {
        // 用户拒绝订阅
        console.info('[上课提醒] 用户拒绝订阅');
        wx.showToast({
          title: '您已拒绝订阅',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('[上课提醒] 订阅失败:', err);
      wx.showToast({
        title: '订阅失败',
        icon: 'none'
      });
    }
  });
},

// 保存订阅状态到服务器
saveSubscriptionStatus() {
  console.info('[上课提醒] 开始保存订阅状态');
  const app = getApp();
  const db = app.getDB();
  const teacherId = wx.getStorageSync('teacherId');
  console.info('[上课提醒] 教师ID:', teacherId);
  
  // 更新教师的订阅状态
  db.collection('teachers').doc(teacherId).update({
    data: {
      hasSubscribed: true,
      subscribeTime: db.serverDate()
    }
  }).then(() => {
    console.info('[上课提醒] 订阅状态已保存成功');
  }).catch(err => {
    console.error('[上课提醒] 保存订阅状态失败:', err);
  });
},

// 设置课程提醒
// 在添加课程时设置提醒
// 在添加课程时设置提醒
async setupCourseReminder(courseId, courseData) {
  try {
    // 参数验证
    if (!courseId || !courseData) {
      console.error('[提醒系统] 设置提醒失败: 参数不完整', { courseId, courseData });
      return;
    }
    
    const app = getApp();
    const db = app.getDB();
    const teacherId = wx.getStorageSync('teacherId');
    
    // 计算提醒时间
    const reminderMinutes = this.parseReminderTime(courseData.reminderTime || '提前5分钟');
    const courseTime = courseData.startTime.split(':');
    const courseHour = parseInt(courseTime[0]);
    const courseMinute = parseInt(courseTime[1]);
    
    // 创建一个用于提醒的日期对象
    const now = new Date();
    const reminderDate = new Date();
    reminderDate.setHours(courseHour);
    reminderDate.setMinutes(courseMinute - reminderMinutes);
    reminderDate.setSeconds(0);
    
    // 添加提醒记录
    await db.collection('reminders').add({
      data: {
        courseId: courseId,
        courseName: courseData.courseName,
        startTime: courseData.startTime,
        classroom: courseData.classroom,
        weekday: parseInt(courseData.weekday),
        weekdayName: ['周日','周一','周二','周三','周四','周五','周六'][parseInt(courseData.weekday)],
        timeSlot: parseInt(courseData.timeSlot),
        reminderTime: courseData.reminderTime || '提前5分钟',
        reminderContent: `${courseData.courseName}即将开始`,
        teacherId: teacherId,
        reminderDateTime: reminderDate, // 添加提醒时间
        createTime: db.serverDate(),
        status: 'pending',
        useLocalNotification: true // 使用本地通知
      }
    });
    
    console.log('[提醒系统] 已为课程设置提醒:', courseData.courseName);
    
  } catch (err) {
    console.error('[提醒系统] 设置课程提醒失败:', err);
  }
},

// 解析提醒时间字符串为分钟数
parseReminderTime(reminderTimeStr) {
  const match = reminderTimeStr.match(/提前(\d+)分钟/);
  if (match && match[1]) {
    return parseInt(match[1]);
  }
  return 5; // 默认提前5分钟
} ,

// 计算下一次课程日期（找到下一个对应星期几的日期）
calculateNextCourseDate(weekday) {
  const today = new Date();
  const currentWeekday = today.getDay(); // 0是周日，1-6是周一到周六
  
  // 将weekday从我们的格式(0-6表示周一到周日)转换为JS的格式(0-6表示周日到周六)
  const jsWeekday = weekday === 6 ? 0 : weekday + 1;
  
  // 计算距离下一次课程还有几天
  let daysUntilNext = jsWeekday - currentWeekday;
  if (daysUntilNext <= 0) {
    daysUntilNext += 7; // 如果是过去的日子，加7天到下周
  }
  
  // 创建下一次课程的日期
  const nextDate = new Date(today);
  nextDate.setDate(today.getDate() + daysUntilNext);
  
  console.info('[调试] 下一次课程日期计算:', {
    今天: today.toLocaleDateString(),
    今天星期几: currentWeekday,
    目标星期几: jsWeekday,
    相差天数: daysUntilNext,
    下次课程日期: nextDate.toLocaleDateString()
  });
  
  return nextDate;
},
  
    // 表单验证
    validateForm() {
      const { formData } = this.data
      if (!formData.courseName?.trim()) {
        wx.showToast({ title: '请输入课程名称', icon: 'none' })
        return false
      }
      if (!formData.className?.trim()) {
        wx.showToast({ title: '请输入班级', icon: 'none' })
        return false
      }
      if (!formData.classroom?.trim()) {
        wx.showToast({ title: '请输入教室', icon: 'none' })
        return false
      }
      return true
    },
  // 初始化日期数据
  initDateData() {
    const year = new Date().getFullYear()
    const years = Array.from({length: 10}, (_, i) => year - 5 + i)
    this.setData({ years })
  },

  // 显示日期选择器
  showDatePicker() {
    this.initDateData()
    this.setData({ showDatePicker: true })
  },

  // 隐藏日期选择器
  hideDatePicker() {
    this.setData({ showDatePicker: false })
  },

  // 日期滚动变化事件
  bindDateChange(e) {
    this.setData({ datePickerValue: e.detail.value })
  },

  // 确认选择日期
  confirmDate() {
    const [yIdx, mIdx, dIdx] = this.data.datePickerValue
    const selectedDate = `${this.data.years[yIdx]}-${this.data.months[mIdx]}-${this.data.days[dIdx]}`
  
    this.setData({
      formData:{
        ...this.data.formData,
        startDate: selectedDate
      },
      showDatePicker: false
    })
    console.log('选择的日期:', selectedDate)
  },
 // 日期格式化方法
 formatDate(date) {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  console.log('date', year,'年', month, '月',day)
  return `${year}-${month}-${day}`
},
getTodayDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
},
// 日期选择回调
handleDateChange(e) {
  console.log('日期选择回调', e)
  const selectedDate = e.detail.value
  this.setData({
    'formData.startDate': selectedDate
  })
  console.log('选择的日期:', selectedDate)
},
   // 下拉刷新处理
   async onPullDownRefresh() {
     console.info('执行了下啦处理.....')
    try {
      
      // 完全重新加载
      wx.showToast({ title: '刷新成功', icon: 'success' });
    } finally {
      wx.stopPullDownRefresh(); // 必须停止刷新
    }
  },
 
// 获取课程详情
// ... existing code ...

// 获取课程详情
async fetchCourseDetail(courseId) {
  try {
    wx.showLoading({ title: '加载中...' });
    const db = wx.cloud.database();
    const res = await db.collection('courses').doc(courseId).get();

    if (res.data) {
      this.setData({
        formData: {
          courseName: res.data.courseName || '',
          className: res.data.className || '',
          classroom: res.data.classroom || '',
          weekday: parseInt(res.data.weekday),
          timeSlot: parseInt(res.data.timeSlot),
          startTime: res.data.startTime || '00:00',
          endTime: res.data.endTime || '00:00',
          reminder: res.data.reminder || false,
          reminderTimeIndex: res.data.reminderTimeIndex || 0,
          // 新增获取 startDate 和 totalWeeks
          startDate: res.data.startDate || '',
          totalWeeks: res.data.totalWeeks || ''
        }
      });

      // 查询关联的学生信息
      const courseStudentsRes = await db.collection('course_students').where({
        courseId: courseId
      }).get();

      const studentIds = courseStudentsRes.data.map(item => item.studentId);
      console.log('studentIds', studentIds);
      if (studentIds.length > 0) {
        const studentsRes = await db.collection('students').where({
          _id: db.command.in(studentIds)
        }).orderBy('createTime', 'desc')// 按创建时间降序排列
        .get();
        console.log('studentsRes', studentsRes);
        this.setData({
          addedStudents: studentsRes.data
        });
      }

      // 查询课程周次信息
      const courseWeeksRes = await db.collection('course_weeks').where({
        courseId: courseId
      }).get();
      console.log('courseWeeksRes', courseWeeksRes);
      // 这里可以根据需求对 courseWeeksRes.data 进行处理，例如存储到某个变量中
      const currentDate = new Date();
      // 格式化为 YYYY-MM-DD 字符串（与时区无关）
     const currentDateString = currentDate.toISOString().split('T')[0]; 
     // 在 fetchCourseDetail 方法中
    // 查找当前周
    const currentWeek = courseWeeksRes.data.find(week => 
    currentDateString >= week.weekStart && 
    currentDateString <= week.weekEnd    
);

this.setData({
  currentWeekNumber: currentWeek?.weekNumber || 0
});

console.log('当前周次:', this.data.currentWeekNumber);
// 处理结果
if (currentWeek) {
  console.log('当前是第', currentWeek.weekNumber, '周');
  this.setData({ currentWeekNumber: currentWeek.weekNumber });
} else {
  console.log('当前不在课程周期内');
  this.setData({ currentWeekNumber: 0 }); // 0 表示未在周期内
}
    }
    wx.hideLoading();
  } catch (err) {
    console.error('获取课程详情失败：', err);
    wx.hideLoading();
    wx.showToast({ title: '获取课程详情失败', icon: 'none' });
  }
},

getTodayDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
},
  // 处理输入框变化
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
        [`formData.${field}`]: value
    });
    console.log('formData222', this.data.formData);
},

  // 处理星期选择
  handleWeekdayChange(e) {
    this.setData({
      'formData.weekday': parseInt(e.detail.value)
    })
  },

  // 处理节次选择
  handleTimeSlotChange(e) {
    this.setData({
      'formData.timeSlot': parseInt(e.detail.value)
    })
  },

  // 处理时间选择
  handleTimeChange(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      [`formData.${type}`]: e.detail.value
    })
  },

  // 处理提醒开关
  handleReminderSwitch(e) {
    this.setData({
      'formData.reminder': e.detail.value
    })
  },

  // 处理提醒时间选择
  handleReminderTimeChange(e) {
    this.setData({
      'formData.reminderTimeIndex': parseInt(e.detail.value)
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    if (!formData.courseName?.trim()) {
      wx.showToast({ title: '请输入课程名称', icon: 'none' })
      return false
    }
    if (!formData.className?.trim()) {
      wx.showToast({ title: '请输入班级', icon: 'none' })
      return false
    }
    if (!formData.classroom?.trim()) {
      wx.showToast({ title: '请输入教室', icon: 'none' })
      return false
    }
    return true
  },

// 提交表单
// 提交表单
async submitForm() {
  try {
    if (!this.validateForm()) return;
    if (this.data.addedStudents.length === 0) {
      wx.showToast({ title: '请至少添加一个学生', icon: 'none' });
      return;
    }

    wx.showLoading({ title: this.data.isEdit ? '保存中...' : '添加中...' });
    const db = wx.cloud.database();
    const _ = db.command;

    // 构造课程数据
    const courseData = {
      ...this.data.formData,
      weekday: parseInt(this.data.formData.weekday),
      timeSlot: parseInt(this.data.formData.timeSlot),
      teacherId: wx.getStorageSync('teacherId'),
      updateTime: db.serverDate()
    };

    let courseId;
    if (this.data.isEdit) {
      // 编辑模式：删除旧数据
      courseId = this.data.courseId;

      // 删除旧周次
      const weeks = await db.collection('course_weeks').where({ courseId }).get();
      for (const w of weeks.data) {
        await db.collection('course_weeks').doc(w._id).remove();
      }

      // 删除旧关联
      const links = await db.collection('course_students').where({ courseId }).get();
      for (const l of links.data) {
        await db.collection('course_students').doc(l._id).remove();
      }
      
      // 删除旧提醒
      await db.collection('reminders').where({ courseId }).remove();

      await db.collection('courses').doc(courseId).update({ data: courseData });
    } else {
      // 新建模式
      const res = await db.collection('courses').add({ data: courseData });
      courseId = res._id;
    }

    // 处理学生数据（防重复）
    const studentNumbers = this.data.addedStudents.map(s => s.studentNumber);
    
    // 1. 查询已存在学生
    const existingRes = await db.collection('students')
      .where({ studentNumber: _.in(studentNumbers) })
      .get();
    const existingMap = new Map(existingRes.data.map(s => [s.studentNumber, s._id]));
    
    // 2. 分离新增和已有学生
    const [existingStudents, newStudents] = this.data.addedStudents.reduce(
      ([exist, news], student) => {
        existingMap.has(student.studentNumber) 
          ? exist.push(existingMap.get(student.studentNumber))
          : news.push(student);
        return [exist, news];
      },
      [[], []]
    );

    // 3. 逐个新增学生
    let newStudentIds = [];
    for (const s of newStudents) {
      const res = await db.collection('students').add({
        data: { studentName: s.studentName, studentNumber: s.studentNumber }
      });
      newStudentIds.push(res._id);
    }

    // 4. 合并所有学生ID
    const allStudentIds = [...existingStudents, ...newStudentIds];

    // 5. 逐个关联到课程
    for (const studentId of allStudentIds) {
      await db.collection('course_students').add({
        data: { courseId, studentId }
      });
    }

    // 处理周次数据（保持不变）
    const totalWeeks = parseInt(this.data.formData.totalWeeks);
    if (isNaN(totalWeeks) || totalWeeks <= 0) {
      wx.showToast({ title: '请输入有效的总周数', icon: 'none' });
      return;
    }

    const start = new Date(this.data.formData.startDate);
    for (let i = 0; i < totalWeeks; i++) {
      const weekStart = new Date(start.getTime() + i * 7 * 86400000);
      await db.collection('course_weeks').add({
        data: {
          courseId,
          weekNumber: i + 1,
          weekStart: weekStart.toISOString().split('T')[0],
          weekEnd: new Date(weekStart.getTime() + 6 * 86400000).toISOString().split('T')[0]
        }
      });
    }

     // 在这里添加对提醒设置函数的调用 - 修复参数传递问题
     if (this.data.formData.reminder && this.data.formData.reminderTimeIndex > 0) {
      // 构造提醒时间字符串
      const reminderTime = this.data.reminderTimes[this.data.formData.reminderTimeIndex];
      
      // 准备完整的课程数据对象
      const reminderCourseData = {
        ...courseData,
        reminderTime: reminderTime
      };
      
      // 正确传递两个参数
      await this.setupCourseReminder(courseId, reminderCourseData);
    }

    wx.hideLoading();
    wx.showToast({ title: '操作成功', icon: 'success' });
    
    // 返回刷新
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    if (prevPage) prevPage.fetchCourseList?.();
    wx.navigateBack();

  } catch (err) {
    console.error('操作失败：', err);
    wx.hideLoading();
    wx.showToast({ title: err.message || '操作失败', icon: 'none' });
  }
}
  
})